/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jboss.seam.scxml.impl.faces;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import org.apache.commons.scxml.SCXMLExecutor;
import org.apache.commons.scxml.TriggerEvent;
import org.apache.commons.scxml.model.ModelException;
import org.jboss.seam.scxml.DialogManager;
import org.jboss.seam.scxml.impl.DialogUtils;
import org.jboss.seam.scxml.impl.invokers.ViewInvoker;

/**
 *
 * @author Waldemar Kłaczyński
 */
public class DialogNavigationHandler extends ConfigurableNavigationHandler {

    private NavigationHandler wrappedNavigationHandler;

    public DialogNavigationHandler(NavigationHandler navigationHandler) {
        this.wrappedNavigationHandler = navigationHandler;
    }
    
    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        DialogManager manager = DialogUtils.getReference(DialogManager.class);
        if (!manager.isStarted() && wrappedNavigationHandler instanceof ConfigurableNavigationHandler) {
            ConfigurableNavigationHandler wrappedConfigurableNavigationHandler = (ConfigurableNavigationHandler) wrappedNavigationHandler;
            return wrappedConfigurableNavigationHandler.getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        DialogManager manager = DialogUtils.getReference(DialogManager.class);
        if (!manager.isStarted() && wrappedNavigationHandler instanceof ConfigurableNavigationHandler) {
            ConfigurableNavigationHandler wrappedConfigurableNavigationHandler = (ConfigurableNavigationHandler) wrappedNavigationHandler;
            return wrappedConfigurableNavigationHandler.getNavigationCases();
        } else {
            return Collections.EMPTY_MAP;
        }
    }

    @Override
    public void handleNavigation(FacesContext context, String fromAction, String outcome) {
        DialogManager manager = DialogUtils.getReference(DialogManager.class);
        if (manager.isStarted()) {
            SCXMLExecutor executor = manager.getRootExecutor();
            try {
                executor.triggerEvent(new TriggerEvent(ViewInvoker.OUTCOME_EVENT_PREFIX + outcome, TriggerEvent.SIGNAL_EVENT));
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
            if (executor.getCurrentStatus().isFinal()) {
                manager.stop();
            }
        }
    }
}
